package practise.leetcode.q2;

import java.util.List;

public class Solution {
    public ListNode addTowNums(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        }
        ListNode result = null;
        ListNode prev = null;
        boolean needAddOne = false;
        while (l1 != null || l2 != null) {
            ListNode addResult = add(l1, l2);

            if (needAddOne) {
                addResult.val = addResult.val + 1;
            }

            if (addResult.val >= 10) {
                addResult.val = addResult.val % 10;
                needAddOne = true;
            }
            else {
                needAddOne = false;
            }
            if (result == null) {
                result = addResult;
            }

            if (prev != null) {
                prev.next = addResult;
            }
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
            prev = addResult;
        }

        if (needAddOne) {
            prev.next = new ListNode(1);
        }

        return result;
    }

    private ListNode add(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        }
        if (l1 == null) {
            return new ListNode(l2.val);
        }
        if (l2 == null) {
            return new ListNode(l1.val);
        }
        return new ListNode(l1.val + l2.val);
    }
}
